package com.nowcoder.community.controller;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.ElasticsearchService;
import com.nowcoder.community.service.LikeService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.utils.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ElasticSearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;


    @GetMapping("/search")
    public String search(@RequestParam("keyword") String keyword, Page page, Model model) throws IOException {
        page.setPath("/search?keyword="+keyword);
        List<DiscussPost> discussPosts = elasticsearchService.searchDiscussPost(keyword, page.getOffset(), page.getLimit());
       long pagesize=elasticsearchService.searchCount(keyword);
        page.setRows((int) pagesize);

        List<Map<String,Object>> list=new ArrayList<>();
        for(DiscussPost discussPost:discussPosts){
            Map<String,Object> map=new HashMap<>();
            map.put("post",discussPost);
            User user = userService.findUserById(discussPost.getUserId());
            map.put("user",user);
            long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST,discussPost.getId());
            map.put("likeCount",likeCount);

            list.add(map);

        }

        model.addAttribute("list",list);
        model.addAttribute("keyword",keyword);

        return "site/search";
        }
}
